-- UIRelicStrengthen
-- Create by cheny3
-- 遗迹扩建

require "game/ui/form/sky_city/UIRelicStrengthenDetail"

-- UIRelicStrengthen继承自Layer
UIRelicStrengthen = class("UIRelicStrengthen", function()
    return cc.Layer:create();
end);

-- 内部函数
local MAX_GRID_ROW    = 2;    -- 单页最大行数
local PAGE_COLUMN     = 3;    -- 列数
local MAX_TAB_NUM     = 3;    -- 标签数量
local tabNames;
local sortItem;

function UIRelicStrengthen.create(openType)
    return UIRelicStrengthen.new(openType);
end

-- 构造函数
function UIRelicStrengthen:ctor(openType)
    -- 初始化
    self:setName("UIRelicStrengthen");
    -- 遗迹强化/复用炼金强化页
    local node = cc.CSLoader:createNode("layout/workshop/WorkshopStrengthen.csb");
    self:addChild(node);
    self.node = node;
    self.openType = openType;

    if self.openType == "awake" then
        tabNames = {getLocStr("tab_text_awake_recruit"), getLocStr("tab_text_awake_skill")};
        titleNames = {getLocStr("tab_text_awake_recruit"), getLocStr("tab_text_awake_skill")};
    else
        tabNames = {getLocStr("tab_text_relic_strengthen"), getLocStr("tab_text_relic_make"), getLocStr("tab_text_relic_medal")};
        titleNames = {getLocStr("tab_text_relic_strengthen"), getLocStr("tab_text_relic_make"), getLocStr("tab_text_relic_medal")};
    end

    local scrollview = findChildByName(self.node, "CT/template/scroll_view");
    self.scrollView = scrollview;
    self.initHeight = scrollview:getInnerContainerSize().height;
    self.scrollView:setVisible(true);

    -- 上下滑动，需要显示上下蒙版
    local mask1 = findChildByName(self.node, "CT/template/mask1");
    mask1:setVisible(true);

    local mask2 = findChildByName(self.node, "CT/template/mask2");
    mask2:setVisible(true);

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 初始化标签页
    self:initTabs();
    self:selectTab(1);

    -- 重绘
    self:initGrids();
    self:redraw();

    -- 适配
    self:resize();
end

-- 初始化标签页
function UIRelicStrengthen:initTabs()
    self.tabList = {};

    local startX = 0;
    local gap = 97;

    local pageMaxNo = MAX_TAB_NUM;

    local tabs = findChildByName(self.node, "CT/tabs");

    for i = 1, pageMaxNo do
        while true do
            local tab = findChildByName(tabs, "tab"..i);
            local icon = findChildByName(tab, "icon");

            icon:loadTexture(getTabIconPath("blue"));
            icon:setTag(i);
            tab:setTag(i);

            if i > #tabNames then
                tab:setVisible(false);
                break;
            else
                tab:setVisible(true);
            end

            -- 第3页如果有的才显示(固定为勋章)
            if #SkyRelicFunctionM.getItemListByPageNo(i, self.openType) < 1 then
                tab:setVisible(false);
                break;
            end

            -- 初始化标签名
            local text = findChildByName(tab, "text");
            local tabStr = tabNames[i];
            local kerning = 0;
            if not isFullWidthLang() then
                kerning = -3;
            end
            TextStyleM.setOutlineStyle(text, TextStyleM.TEXT_OUTLINE_SIZE, TextStyleM.TEXT_OUTLINE_COLOR_DARK);
            TextStyleM.setTextStyle(text, TextStyleM.TEXT_SIZE_SMALL2, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true, kerning, nil, nil, nil, nil, true, TextStyleM.getTextScale(tabStr, 6));
            text:setString(tabStr);

            if startX == 0 and i == 1 then
                startX = tab:getPositionX();
            end

            table.insert(self.tabList, tab);
            tab:setVisible(true);

            icon:addTouchEventListener(function (sender, eventType)
                if eventType == ccui.TouchEventType.ended then
                    AudioM.playFx("button_click");
                    -- 选中页签处理
                    self:selectTab(sender:getTag());

                    self:initGrids();
                    self:redraw();
                end
            end);

            break;
        end
    end

    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        tab:setPositionX(startX + (i - 1) * gap);
        tab:setPositionY(tab:getPositionY() + 100);
    end

    -- tab的动画效果
    performWithDelay(self, function() self:playTabEffect(); end, 0.2);
end

-- 页签动画效果
function UIRelicStrengthen:playTabEffect()
    -- 带窗口动画播放结束后，页签从上面往下掉
    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        local delay = 0.2 * (i - 1);
        self:dropEffect(tab, delay);
        if tab.bubbleParent and tab.bubbleParent.isVisible then
            tab.bubbleParent:setVisible(false);
            tab.bubbleParent:setOpacity(0);
            local function delayShow()
                local fadeIn = cc.FadeIn:create(0.4);
                tab.bubbleParent:setVisible(true);
                tab.bubbleParent:runAction(fadeIn);
            end
            performWithDelay(self, delayShow, delay + 0.4);
        end
    end
end

-- 掉落动画
function UIRelicStrengthen:dropEffect(node, delay)
    local pos = cc.p(node:getPosition());
    local delay = cc.DelayTime:create(delay);
    local moveDown = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100 - 5));
    local moveBack = cc.MoveTo:create(0.2, cc.p(pos.x, pos.y - 100));
    local action = cc.Sequence:create(delay, moveDown, moveBack);
    node:runAction(action);
end

-- 初始化格子
function UIRelicStrengthen:initGrids(notTop)
    local pageNo = self.selectIndex;

    -- 如果有正在播放的光效，保存下来
    if self.playingStrengthenId ~= nil then
        self.curStrengthenId = self.playingStrengthenId;
    end

    -- 获取列表
    local finalList = self:getItemListByPageNo(pageNo);

    if #finalList == 0 then
        return;
    end

    table.sort(finalList, sortItem);

    -- 图标间距(横向)
    local wGap = 10;

    -- 图标间距(纵向)
    local hGap = 25;

    -- 图标宽度
    local iconWidth = 140;

    -- 图片高度
    local iconHeight = 150;

    local topHGap  = 25;
    local bottomHGap  = 50;
    local leftWGap = 10;

    -- 总数
    local totalCount = #finalList;

    self.scrollView.rows = {};
    self.scrollView:removeAllChildren();

    local itemNode = cc.CSLoader:createNode("layout/workshop/StrengthenItem.csb");
    local hintNode = itemNode:getChildByName("hint");
    replaceNodeWithWidget(hintNode);

    -- @param windowNode    界面节点
    -- @param scrollNode    容器节点
    -- @param itemNode      单元格的节点
    -- @param totalNum      单元格总数
    -- @param maxRowNum     最大行数
    -- @param pageColNum    单页可以显示下的列数
    -- @param wGap          单元格间距(横向) 这里作为最小值使用
    -- @param hGap          单元格间距(纵向)
    -- @param iconWidth     单元格宽度
    -- @param iconHeight    单元格高度
    -- @param topHGap       上方留
    -- @param leftWGap      左右留白  这里作为最小值使用
    -- @param touchEvent    点击事件注册函数
    initScrollGridsVertical(self, self.scrollView, itemNode, totalCount, MAX_GRID_ROW, PAGE_COLUMN, wGap, hGap, iconWidth, iconHeight, topHGap, bottomHGap, leftWGap, nil);

    if not notTop then
        scrollToTop(self.scrollView);
    end
end

-- 改变标签页状态
function UIRelicStrengthen:selectTab(index)
    self.selectIndex = index;

    local blendColor = TextStyleM.TEXT_COLOR_BLEND;
    local normalColor = TextStyleM.TEXT_COLOR_NORMAL;
    for i = 1, #self.tabList do
        local tab = self.tabList[i];
        local light = tab:getChildByName("light");
        local text = findChildByName(tab, "text");
        local bubbleParent = findChildByName(self.node, "CT/bubble_parent"..i);
        bubbleParent:setVisible(false);
        local bubble = findChildByName(bubbleParent, "bubble");
        bubbleParent:setCascadeColorEnabled(false);
        bubble:setVisible(false);

        if tab:getTag() ~= index then
            checkBlueBubbleStatus(bubble, self:hasBubbles(tab:getTag()));
            -- 先隐藏
            bubbleParent:setVisible(false);
            bubbleParent.isVisible = bubble:isVisible();
        end
        tab.bubbleParent = bubbleParent;

        if index == tab:getTag() then
            tab:setColor(normalColor);
            light:setVisible(true);
            text:setTextColor(TextStyleM.TEXT_COLOR_BROWN_YELLOW);
        else
            tab:setColor(blendColor);
            light:setVisible(false);
            text:setTextColor(TextStyleM.TEXT_COLOR_BROWN_YELLOW);
        end
    end

    self.subHeadLabel:setString(titleNames[self.selectIndex]);
end

-- 页签内有可强化的项
function UIRelicStrengthen:hasBubbles(pageNo)
    return SkyRelicFunctionM.needShowBubbleForIndex(pageNo, self.openType);
end

-- 适配
function UIRelicStrengthen:resize()
    local node = self.node;

    -- bg/bg缩放至合适大小
    AlignM.fitToScreen(node, "bg");

    -- CENTER置于顶部并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 重绘界面
function UIRelicStrengthen:redraw()
    local pageNo = self.selectIndex;

    -- 获取列表
    local finalList = self:getItemListByPageNo(pageNo);

    if #finalList == 0 then
        return;
    end

    table.sort(finalList, sortItem);

    -- 显示信息
    for i = 1, #finalList do
        local grid = self.scrollView:getChildByName("item" .. i);
        if grid then
            --  初始化格子信息
            self:initItem(grid, finalList[i]);
        end
    end
end

-- 排序
function sortItem(item1, item2)
    return item1.index < item2.index;
end

-- 初始化单个项
function UIRelicStrengthen:initItem(node, info)
    local id = info.id;
    -- 当前等级
    local level = SkyRelicFunctionM.getLevel(id);
    local maxLevel = info.max_level;

    -- 图标
    local icon = findChildByName(node, "icon");
    local fileName = SkyRelicFunctionM.query(id, "icon");

    -- 勋章的话直接取用物品图标
    local rule = SkyRelicFunctionM.query(id, "rule");
    if rule == "sky_medal" then
        local medalId = SkyRelicFunctionM.query(id, "medal_id");
        fileName = ItemM.query(medalId, "icon");
        icon:loadTexture(getItemIconPath(fileName));
    elseif rule == "slime" then
        -- 英雄的图标
        local tech = SkyRelicFunctionM.query(id, "tech");
        local petId = tech["pet_id"];
        icon:loadTexture(getHeroIconPath(petId));
    elseif rule == "ariship_skill" then
        -- 秘宝图标
        local condition = SkyRelicFunctionM.query(id, "condition");
        local skillId = condition["skill_id"];
        icon:loadTexture(getAirShipSkillIconPath(skillId))
    else
        icon:loadTexture(getRelicFunctionIconPath(fileName));
    end

    local scale = SkyRelicFunctionM.query(id, "scale");
    if type(scale) == "number" and scale > 0 then
        icon:setScale(scale / 100);
    end

    -- 背景
    local frame = findChildByName(node, "frame");
    fileName = SkyRelicFunctionM.query(id, "bg");
    frame:loadTexture(getWorkshopStrengthenIconPath("bg3"));

    -- 是否可以强化
    local canStrengthen = SkyRelicFunctionM.canDevelop(id);

    -- 名称等级
    local levelLabel = findChildByName(node, "level");
    local color;

    if canStrengthen ~= true then
        color = TextStyleM.TEXT_COLOR_LIGHT_BLUE;
    else
        color = TextStyleM.TEXT_COLOR_BRIGHT_YELLOW;
    end
    TextStyleM.setTextStyle(levelLabel, 28, color, true, nil, nil, nil, nil, nil, true);
    TextStyleM.setShadowStyle(levelLabel, cc.size(0, -2.5));
    levelLabel:getVirtualRenderer():setAdditionalKerning(getLocKerning() -3);
    levelLabel:setPositionY(levelLabel:getPositionY() - 3);

    if level >= maxLevel then
        levelLabel:setString(getLocStr("level_max"));
    else
        levelLabel:setString(string.format(getLocStr("level_flag"), level));
    end

    -- 秘宝不显示LV.MAX
    if SkyRelicFunctionM.query(id, "rule") == "ariship_skill" then
        levelLabel:setVisible(false);
    end

    -- 等级为0时，背景框透明，lv.x 不显示
    if level == 0 then
        frame:setOpacity(96);
        icon:setOpacity(128);
        levelLabel:setVisible(false);
    end

    -- 泡泡节点
    local hintNode = findChildByName(node, "hint");

    -- 点击处理
    local frame = findChildByName(node, "frame");
    frame:addTouchEventListener(function (sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- TODO
            -- 屏蔽掠夺许可证
            --[[if info.id == 4 then
                alert(getLocStr("relic_rob_tip"));
                return;
            end--]]

            AudioM.playFx("ui_open1");
            local uiForm = UIRelicStrengthenDetail.create(info);
            UIMgr.getCurrentScene():addForm(uiForm);
        end
    end);

    -- 可以强化的话，显示右上角的气泡(只提醒一次，玩家查看后则不再提醒，重新登陆会再次提醒)
    local showBubble = SkyRelicFunctionM.needShowBubble(id, level);
    checkBlueBubbleStatus(hintNode, showBubble);
    if showBubble then
        -- 只显示一次，打开页签后自动将标记置为已提醒
        SkyRelicFunctionM.setStrengthenItemReminded(id, level);
    end

    -- 当前强化ID
    if self.curStrengthenId ~= nil and self.curStrengthenId == id then
        playEffect(frame, 1180, 75, 85);

        local levelLabel = findChildByName(node, "level");
        commonTextEffect(levelLabel);

        -- 标记正在播放强化光效的项
        self.playingStrengthenId = id;
        local function doneWithPlaying()
            self.playingStrengthenId = nil;
        end
        performWithDelay(self, doneWithPlaying, 1);
        self.curStrengthenId = 0;
    end
end

-- 播放强化特效
function UIRelicStrengthen:playStrengthenEffect(id)
    self.curStrengthenId = id;
end

-- 获取本页签的物品项数目
function UIRelicStrengthen:getItemListByPageNo(pageNo)
    local list = SkyRelicFunctionM.getItemListByPageNo(pageNo, self.openType);
    local ret = {};
    for _, info in pairs(list) do
        if SkyRelicFunctionM.checkPreCondition(info.id)
            or SkyRelicFunctionM.getLevel(info.id) > 0 then
            -- 满足前提条件/已经升级过的才显示
            table.insert(ret, info);
        end
    end

    return ret;
end

-- 注册事件处理回调函数
function UIRelicStrengthen:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(eventType)
        if eventType == "exit" then
            EventMgr.removeAll("UIRelicStrengthen");
        elseif eventType == "enter" then
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIRelicStrengthen", event.FOCUS_CHANGED, function(para)
        if para["get"] == "UIRelicStrengthen" then
            UIMgr:getCurrentScene().topMenu:show(TOPMENU_FRAME_MONEY, TOPMENU_FRAME_RUINS_SCRAP);
        elseif para["lose"] == "UIRelicStrengthen" then
        end
    end);

    -- 注册获得焦点的回调
    EventMgr.register("UIRelicStrengthen", event.RELIC_DEVELOP, function(para)
        self:selectTab(self.selectIndex);
        self:initGrids(true);
        self:redraw();
    end);
end

-- 注册点击事件
function UIRelicStrengthen:registerTouchEvent()
    -- 设置标题样式
    local titleLabel = findChildByName(self.node, "CT/template/title");
    if self.openType == "awake" then
        titleLabel:setString(getLocStr("awake_strengthen_title"));
    else
        titleLabel:setString(getLocStr("relic_title"));
    end
    TextStyleM.setTitleStyle(titleLabel);

    -- 副标题
    local subHeadLabel = findChildByName(self.node, "CT/template/subhead");
    TextStyleM.setSubheadStyle(subHeadLabel);
    self.subHeadLabel = subHeadLabel;

    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node,"BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("ship_return");
            -- 关闭当前界面
            UIMgr.getCurrentScene():removeFormByName("UIRelicStrengthen");
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 说明按钮
    local tip = findChildByName(self.node, "CT/tip");
    local oriScale = tip:getScale();
    local function onTipCkick(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            tip:setScale(oriScale - 0.1);
        elseif eventType == ccui.TouchEventType.canceled then
            tip:setScale(oriScale);
        elseif eventType == ccui.TouchEventType.ended then
            tip:setScale(oriScale);
            -- 说明界面
            AudioM.playFx("button_click");
            -- TODO
        end
    end
--    tip:setVisible(true);
    tip:addTouchEventListener(onTipCkick);
end
